package logic

import (
	"alibaba-register/models/cache"
	"alibaba-register/models/mysql"
	"alibaba-register/pkg"
	"context"
	"fmt"

	"alibaba-register/alibabarpc/alibabarpc"
	"alibaba-register/alibabarpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *alibabarpc.LoginRequest) (*alibabarpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	getSms := cache.Rdb.Get(l.ctx, "sendSms"+"login"+in.Mobile)
	if getSms.Val() != in.CaptSms {
		return nil, fmt.Errorf("短信验证码错误,请重新输入")
	}

	getImage := cache.Rdb.Get(l.ctx, "captcha"+"login"+in.Mobile)
	if getImage.Val() != in.CaptImage {
		return nil, fmt.Errorf("图形证码错误,请重新输入")
	}

	var accountFind mysql.Account
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&accountFind)
	if accountFind.ID == 0 {
		return nil, fmt.Errorf("账号未注册,请先注册后登录")
	}

	if accountFind.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误,请重新输入")
	}

	//删除验证码缓存
	cache.Rdb.Del(l.ctx, "sendSms"+"login"+in.Mobile)
	cache.Rdb.Del(l.ctx, "captcha"+"login"+in.Mobile)
	return &alibabarpc.LoginResponse{Id: int64(accountFind.ID)}, nil
}
